package demo02;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class test4 {
    public static void main(String[] args) {
        List<String> students = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new FileReader("names.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                students.add(line);
            }
        } catch (IOException e) {
            e.getMessage();
            return;
        }

        File selectedStudentsFile = new File("selected_students.txt");
        Set<String> selectedStudents = new HashSet<>();

        try {
            if (!selectedStudentsFile.exists()) {
                selectedStudentsFile.createNewFile();
            } else {
                try (BufferedReader fileReader = new BufferedReader(new FileReader(selectedStudentsFile))) {
                    String name;
                    while ((name = fileReader.readLine()) != null) {
                        selectedStudents.add(name);
                    }
                }
            }

            Random random = new Random();
            int randomIndex;
            String selectedStudent = null;

            do {
                randomIndex = random.nextInt(students.size());
                selectedStudent = students.get(randomIndex);
            } while (selectedStudents.contains(selectedStudent));

            selectedStudents.add(selectedStudent);
            System.out.println("随机学生为: " + selectedStudent);

            try (BufferedWriter fileWriter = new BufferedWriter(new FileWriter(selectedStudentsFile, true))) {
                fileWriter.write(selectedStudent + "\n");
            } catch (IOException e) {
                e.getMessage();
            }

            int round = selectedStudents.size();
            if (round >= 10) {
                selectedStudents.clear();
                selectedStudentsFile.delete();
                selectedStudentsFile.createNewFile();
            }
        } catch (IOException e) {
            e.getMessage();
        }
    }
}